﻿using System.Reflection;

namespace Newtonsoft.Json.Serialization
{
    public class ListValueProvider<T> : ExpressionValueProvider, IValueProvider
    {
        private readonly MemberInfo _member;
        private bool _isConvertNullToEmpty;

        public ListValueProvider(MemberInfo member, bool isConvertNullToEmpty)
            : base(member)
        {
            var type = Dyao.Book.Core.ReflectionHelper.GetMemberUnderlyingType(member);
            if (!typeof(IList<T>).IsAssignableFrom(type))
            {
                throw new ArgumentException($"This value provider can only be used with {typeof(IList<T>).Name} and that sub class type.");
            }

            this._member = member;
            this._isConvertNullToEmpty = isConvertNullToEmpty;
        }

        public new object GetValue(object target)
        {
            object value = base.GetValue(target);

            if (_isConvertNullToEmpty && value == null)
            {
                if (_member.DeclaringType.IsArray)
                {
                    return new T[0];
                }

                return new List<T>();
            }

            return value;
        }

        public new void SetValue(object target, object value)
        {
            base.SetValue(target, value);
        }
    }
}
